package com.summer.authentication.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.summer.authentication.mapper.XcUserMapper;
import com.summer.authentication.model.AuthParams;
import com.summer.authentication.model.dto.XcUserDto;
import com.summer.authentication.pojo.XcUser;
import com.summer.authentication.service.AuthService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

// 密码模式认证
@Service("password")
public class PasswordAuth implements AuthService {

    @Autowired
    private XcUserMapper usersMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public XcUserDto authExecute(AuthParams authParams) {

        //1. 调用验证码服务校验验证码
        String checkCode = authParams.getCheckCode();
        String checkCodeInRedis = (String) redisTemplate.opsForValue().get(authParams.getCheckCodeKey());

        if (StringUtils.isEmpty(checkCodeInRedis)){
            throw new RuntimeException("获取不到验证码");
        }
        if (!checkCodeInRedis.equals(checkCode)){
            throw new RuntimeException("验证码错误");
        }

        //2. 判断用户是否存在
        // TODO 根据账号去数据库查询...
        XcUser xcUser = usersMapper
                .selectOne(new LambdaQueryWrapper<XcUser>().eq(XcUser::getUsername, authParams.getUsername()));
        if (xcUser == null) {
            throw new RuntimeException("用户不存在");
        }

        //3. 比对密码
        boolean matches = passwordEncoder.matches(authParams.getPassword(),xcUser.getPassword());
        if (!matches){
            throw new RuntimeException("密码错误");
        }

        //4. 认证成功返回userDto，password置空操作不在这
        XcUserDto userDto = new XcUserDto();
        BeanUtils.copyProperties(xcUser, userDto);
        return userDto;
    }
}
